#!/usr/bin/env bash
# shellcheck disable=SC2086


iface="${iface:-enp0s8}"


wait4x_image="${wait4x_image:-atkrad/wait4x:2.12}"
nginx_image="${nginx_image:-nginx:1.22.1-alpine}"
mysql5_image="${mysql5_image:-mysql:5.7.41}"
mysql8_image="${mysql8_image:-mysql:8.0.23}"
adminer_image="${adminer_image:-adminer:4.8.1}"
mongo_image="${mongo_image:-mongo:7.0.3}"
rocketmq_image="${rocketmq_image:-dyrnq/rocketmq:4.9.7}"
redis_image="${redis_image:-redis:6.0.19}"
elasticsearch7_image="${elasticsearch7_image:-elasticsearch:7.17.7}"
elasticsearch8_image="${elasticsearch8_image:-elasticsearch:8.11.1}"
kibana7_image="${kibana7_image:-kibana:7.17.7}"
kibana8_image="${kibana8_image:-kibana:8.11.1}"
nacos_image="${nacos_image:-nacos/nacos-server:v2.3.2}"
minio_image="${minio_image:-minio/minio:RELEASE.2022-11-29T23-40-49Z}"
proxy="${proxy:-192.168.6.111:8118}"

while [ $# -gt 0 ]; do
    case "$1" in
        --iface|-i)
            iface="$2"
            shift
            ;;
        --proxy)
            proxy="$2"
            shift
            ;;
        --*)
            echo "Illegal option $1"
            ;;
    esac
    shift $(( $# > 0 ? 1 : 0 ))
done

ip4=$(/sbin/ip -o -4 addr list "${iface}" | awk '{print $4}' |cut -d/ -f1 | head -n1);

curl_opts="";
if [ -n "${proxy}" ]; then
  curl_opts="-x $proxy"
fi

command_exists() {
    command -v "$@" > /dev/null 2>&1
}


fun_system() {
## 设置时区

timedatectl set-timezone "Asia/Shanghai"

## 关闭防火墙

systemctl is-active firewalld >/dev/null 2>&1 && systemctl disable --now firewalld
systemctl is-active dnsmasq >/dev/null 2>&1 && systemctl disable --now dnsmasq
systemctl is-active apparmor >/dev/null 2>&1 && systemctl disable --now apparmor
systemctl is-active ufw >/dev/null 2>&1 && systemctl disable --now ufw

## 关闭swap

#sed -ri 's/.*swap.*/#&/' /etc/fstab
swapoff -a && sysctl -w vm.swappiness=0
sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab

## 关闭selinux

if [ -f /etc/selinux/config ]; then sed -i.bak 's@enforcing@disabled@' /etc/selinux/config; fi
command_exists setenforce && setenforce 0
command_exists getenforce && getenforce && sestatus

## sysctl设置

cat > /etc/sysctl.d/mysysctl.conf << 'EOF'
fs.file-max = 52706963
fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 1048576
fs.may_detach_mounts = 1
fs.nr_open = 52706963
kernel.core_uses_pid = 1
kernel.msgmax = 65535
kernel.msgmnb = 65535
kernel.pid_max = 4194303
kernel.shmall = 4294967296
kernel.shmmax = 68719476736
kernel.softlockup_all_cpu_backtrace = 1
kernel.softlockup_panic = 1
#kernel.sysrq = 1
net.bridge.bridge-nf-call-arptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.core.netdev_max_backlog = 16384
net.core.rmem_max = 16777216
net.core.somaxconn = 32768
net.core.wmem_max = 16777216
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.all.route_localnet = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.lo.arp_announce = 2
net.ipv4.ip_forward = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.neigh.default.gc_stale_time = 120
net.ipv4.neigh.default.gc_thresh1 = 8192
net.ipv4.neigh.default.gc_thresh2 = 32768
net.ipv4.neigh.default.gc_thresh3 = 65536
net.ipv4.tcp_fin_timeout = 20
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_max_orphans = 32768
net.ipv4.tcp_max_syn_backlog = 8096
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_orphan_retries = 3
net.ipv4.tcp_retries2 = 2
net.ipv4.tcp_rmem = 4096 12582912 16777216
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_wmem = 4096 12582912 16777216
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.netfilter.nf_conntrack_max = 25000000
net.netfilter.nf_conntrack_tcp_timeout_close = 3
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_established = 180
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 12
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.nf_conntrack_max = 25000000
vm.max_map_count = 262144
vm.min_free_kbytes = 262144
vm.overcommit_memory = 1
vm.panic_on_oom = 0
vm.swappiness = 0
EOF


sysctl --system

## limits 修改

cat > /etc/security/limits.conf <<'EOF'
*       soft        core        unlimited
*       hard        core        unlimited
*       soft        nproc       1000000
*       hard        nproc       1000000
*       soft        nofile      1000000
*       hard        nofile      1000000
*       soft        memlock     32000
*       hard        memlock     32000
*       soft        msgqueue    8192000
*       hard        msgqueue    8192000
root       soft        core        unlimited
root       hard        core        unlimited
root       soft        nproc       1000000
root       hard        nproc       1000000
root       soft        nofile      1000000
root       hard        nofile      1000000
root       soft        memlock     32000
root       hard        memlock     32000
root       soft        msgqueue    8192000
root       hard        msgqueue    8192000
EOF


## 加载linux内核模块

if ! systemctl is-active systemd-modules-load.service >/dev/null 2>&1; then
    systemctl enable systemd-modules-load.service
fi

cat > /etc/modules-load.d/90-net.conf<<EOF
overlay
br_netfilter
EOF

systemctl daemon-reload && systemctl restart systemd-modules-load.service

lsmod | grep br_netfilter


## rsyslog remove .mount logs

if systemctl is-active rsyslog; then

cat > /etc/rsyslog.d/01-blocklist.conf <<'EOF'
if $msg contains "run-docker-runtime" and $msg contains ".mount: Succeeded." then {
    stop
}
if $msg contains "run-containerd-runc" and $msg contains ".mount: Succeeded." then {
    stop
}
if $msg contains "crun" and $msg contains ".mount:" then {
    stop
}
EOF
systemctl restart rsyslog

fi



if systemctl is-active systemd-resolved; then

dns_str="8.8.8.8 114.114.114.114"

echo "${dns_str}"
mkdir -p /etc/systemd/resolved.conf.d/
cat >/etc/systemd/resolved.conf.d/99-dns.conf << EOF
[Resolve]
DNSStubListener=no
DNS=${dns_str}
EOF
ln -s -f /run/systemd/resolve/resolv.conf /etc/resolv.conf
systemctl daemon-reload && systemctl restart systemd-resolved.service && systemctl status -l systemd-resolved.service --no-pager && cat /etc/resolv.conf
fi

sed -i 's|^PasswordAuthentication.*|PasswordAuthentication yes|g' /etc/ssh/sshd_config && systemctl restart sshd
}

fun_pkg() {
while true ; do
  sed -i 's@//.*archive.ubuntu.com@//mirrors.ustc.edu.cn@g' /etc/apt/sources.list && \
  sed -i 's/security.ubuntu.com/mirrors.ustc.edu.cn/g' /etc/apt/sources.list && \
  apt update && \
  apt install -y dos2unix apt-transport-https curl iptables wget vim psmisc procps iproute2 tree jq gnupg2 netcat nmap htop locales gettext difference ca-certificates openssh-client unzip less ipset net-tools ipvsadm xz-utils conntrack xfsprogs && \
  break
done
}

fun_add_mynet(){
  docker network inspect mynet &>/dev/null || docker network create --subnet 172.18.0.0/16 --gateway 172.18.0.1 --driver bridge mynet
}









fun_install_mysql(){
docker rm -f mysql57 2>/dev/null || true
docker rm -f mysql8 2>/dev/null || true


mkdir -p $HOME/var/lib/mysql
docker run -d --name mysql57 \
--restart always \
--network mynet \
-e MYSQL_ROOT_PASSWORD=666666 \
-v $HOME/var/lib/mysql:/var/lib/mysql \
-p 3306:3306 \
${mysql5_image} --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --default-time-zone=+8:00

mkdir -p $HOME/var/lib/mysql8
docker run -d --name mysql8 \
--restart always \
--network mynet \
-e MYSQL_ROOT_PASSWORD=666666 \
-v $HOME/var/lib/mysql8:/var/lib/mysql \
-p 13306:3306 \
${mysql8_image} --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --default-time-zone=+8:00 --innodb-dedicated-server=on

docker rm -f adminer 2>/dev/null || true
docker run -d --name=adminer --restart always --network mynet -p 18080:8080 ${adminer_image}




}

fun_install_mongo(){
docker rm -f mongo 2>/dev/null || true
mkdir -p $HOME/var/lib/mongo
docker run -d \
--name mongo \
--restart always \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=666666 \
-v $HOME/var/lib/mongo:/data/db \
-p 27017:27017 \
--network mynet \
${mongo_image}

}
#wait4x_ver="v2.13.0"
#curl -fSL -# --retry 30 https://files.m.daocloud.io/github.com/atkrad/wait4x/releases/download/${wait4x_ver}/wait4x-linux-amd64.tar.gz | tar -xzv -C /usr/local/bin/ wait4x

fun_initdb(){
  docker run --net host --rm --name='wait4x' ${wait4x_image} mysql root:666666@tcp\(127.0.0.1:3306\)/mysql --interval 1s --timeout 360s && \
  docker run -it --rm --network mynet  ${mysql5_image} mysql --host mysql57 --user root --password=666666 --loose-default-character-set=utf8 -e "CREATE DATABASE if not exists seckill DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;show databases;"

  docker run --net host --rm --name='wait4x' ${wait4x_image} mysql root:666666@tcp\(127.0.0.1:13306\)/mysql --interval 1s --timeout 360s && \
  docker run -it --rm --network mynet  ${mysql8_image} mysql --host mysql8 --user root --password=666666 -e "CREATE DATABASE if not exists seckill DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;show databases;"

  if [ -e /vagrant ] && [ ! -f /SQL_OK ]; then
    echo "will source SQL"
    docker run -it --rm --network mynet  -v /vagrant:/vagrant ${mysql5_image} mysql --host mysql57 --user root --password=666666 --loose-default-character-set=utf8 -e "use seckill; source /vagrant/sql/seckill.sql;" && \
    docker run -it --rm --network mynet  -v /vagrant:/vagrant ${mysql8_image} mysql --host mysql8 --user root --password=666666 --loose-default-character-set=utf8 -e "use seckill; source /vagrant/sql/seckill.sql;" && \
    touch /SQL_OK
  fi
}

fun_install_rocketmq(){

docker rm -f mqnamesrv1 2>/dev/null || true

mkdir -p $HOME/var/lib/mqnamesrv1/logs
mkdir -p $HOME/var/lib/mqnamesrv1/store

chown -R 3000:3000 $HOME/var/lib/mqnamesrv1
docker run -d \
--name mqnamesrv1 \
--restart always \
-e TZ="Asia/Shanghai" \
-e JAVA_OPT_EXT="-Duser.home=/home/rocketmq -Xms512m -Xmx512m -Xmn128m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m" \
-v $HOME/var/lib/mqnamesrv1/logs:/home/rocketmq/logs \
-v $HOME/var/lib/mqnamesrv1/store:/home/rocketmq/store \
-p 9876:9876 \
--network mynet \
${rocketmq_image} mqnamesrv



cat > /tmp/broker.sed<<EOF
brokerClusterName=DefaultCluster
brokerName=_BROKERNAME
brokerId=0
namesrvAddr=_NAMESRVADDR
defaultTopicQueueNums=4
autoCreateTopicEnable=true
autoCreateSubscriptionGroup=true
listenPort=10911
deleteWhen=04
fileReservedTime=120
mapedFileSizeCommitLog=1073741824
mapedFileSizeConsumeQueue=300000
diskMaxUsedSpaceRatio=88

# 存储路径
#storePathRootDir=/rocketmq/store

# commitLog 存储路径
#storePathCommitLog=/rocketmq/store/commitlog

# 消费队列存储
#storePathConsumeQueue=/rocketmq/store/consumequeue

# 消息索引存储路径
#storePathIndex=/rocketmq/store/index

# checkpoint 文件存储路径
#storeCheckpoint=/rocketmq/store/checkpoint

# abort 文件存储路径
#abortFile=/rocketmq/store/abort
# 限制的消息大小
maxMessageSize=65536
#flushCommitLogLeastPages=4
#flushConsumeQueueLeastPages=2
#flushCommitLogThoroughInterval=10000
#flushConsumeQueueThoroughInterval=60000
# Broker的角色
# ASYNC_MASTER 异步复制Master
# SYNC_MASTER 同步双写Master
# SLAVE
brokerRole=ASYNC_MASTER
# 刷盘方式
# ASYNC_FLUSH 异步刷盘
# SYNC_FLUSH 同步刷盘
flushDiskType=ASYNC_FLUSH
# 发消息线程池数量
#sendMessageThreadPoolNums=128
# 拉消息线程池数量
#pullMessageThreadPoolNums=128
waitTimeMillsInSendQueue=600
brokerIP1=${ip4}
EOF


sed -e "s@_BROKERNAME@mqbroker1@g" -e "s@_NAMESRVADDR@mqnamesrv1:9876@" /tmp/broker.sed > $HOME/mqbroker1.conf


docker rm -f mqbroker1 2>/dev/null || true

mkdir -p $HOME/var/lib/mqbroker1/logs
mkdir -p $HOME/var/lib/mqbroker1/store

chown -R 3000:3000 $HOME/var/lib/mqbroker1
docker run -d \
--name mqbroker1 \
--restart always \
-e TZ="Asia/Shanghai" \
-e JAVA_OPT_EXT="-Duser.home=/home/rocketmq -Xms512m -Xmx512m -Xmn128m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m" \
-v $HOME/var/lib/mqbroker1/logs:/home/rocketmq/logs \
-v $HOME/var/lib/mqbroker1/store:/home/rocketmq/store \
-v $HOME/mqbroker1.conf:/etc/rocketmq/broker.conf \
-p 10909:10909 \
-p 10911:10911 \
-p 10912:10912 \
--network mynet \
${rocketmq_image} mqbroker -c /etc/rocketmq/broker.conf

}




fun_install_redis(){
mkdir -p -v $HOME/var/lib/redis
cat >$HOME/redis.conf<<EOF
port 6379
bind 0.0.0.0
appendonly yes
EOF

docker rm -f redis 2>/dev/null || true;
docker run -d --network mynet \
--name redis \
--restart always \
-p 6379:6379 \
-v $HOME/redis.conf:/usr/local/etc/redis/redis.conf \
-v $HOME/var/lib/redis:/data \
${redis_image} redis-server /usr/local/etc/redis/redis.conf
}

fun_install_es() {

if [ "$1" == "7" ]; then
  ES_DIR=$HOME/var/lib/elasticsearch7
  elasticsearch_image="${elasticsearch7_image}"
  ik_url="https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.17.7/elasticsearch-analysis-ik-7.17.7.zip"
  port_http=9200
  port_tcp=9300
  name="es7"
else
  ES_DIR=$HOME/var/lib/elasticsearch8
  elasticsearch_image="${elasticsearch8_image}"
  ik_url="https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v8.11.1/elasticsearch-analysis-ik-8.11.1.zip"
  port_http=19200
  port_tcp=19300
  name="es8"
fi


#rm -rf $ES_DIR/;
mkdir -p -v $ES_DIR/data
mkdir -p -v $ES_DIR/logs
mkdir -p -v $ES_DIR/plugins



docker run -itd --rm --name elasticsearch-tmp ${elasticsearch_image} sleep 10
docker cp elasticsearch-tmp:/usr/share/elasticsearch/config $ES_DIR

curl -fSL -# -o /tmp/ik.zip $curl_opts $ik_url

mkdir -p -v $ES_DIR/plugins/ik
rm -rf $ES_DIR/plugins/ik/*
unzip /tmp/ik.zip -d $ES_DIR/plugins/ik
chown -R 1000:1000 $ES_DIR/

## run elasticsearch

if [ -f $ES_DIR/config/elasticsearch.yml ]; then
  cat $ES_DIR/config/elasticsearch.yml;
fi


docker rm -f $name 2>/dev/null || true;
docker run -d --network mynet \
--name $name \
--restart always \
--privileged \
-e "TZ=Asia/shanghai" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
-e "discovery.type=single-node" \
-e "xpack.security.enabled=false" \
-p $port_http:9200 \
-p $port_tcp:9300 \
-v $ES_DIR/config:/usr/share/elasticsearch/config \
-v $ES_DIR/data:/usr/share/elasticsearch/data \
-v $ES_DIR/logs:/usr/share/elasticsearch/logs \
-v $ES_DIR/plugins:/usr/share/elasticsearch/plugins \
${elasticsearch_image}
}




fun_install_kibana(){


if [ "$1" == "7" ]; then
  KIBANA_DIR=$HOME/var/lib/kibana7
  kibana_image="${kibana7_image}"
  port_http=5601
  name="kibana7"
  es_host="http://es7:9200"
else
  KIBANA_DIR=$HOME/var/lib/kibana8
  kibana_image="${kibana8_image}"
  port_http=15601
  name="kibana8"
  es_host="http://es8:9200"
fi


# rm -rf $ES_DIR/;

# rm -rf $KIBANA_DIR;
mkdir -p -v $KIBANA_DIR

docker rm -f kibana-tmp 2>/dev/null || true;
docker run -itd --rm --name kibana-tmp ${kibana_image} sleep 10
docker cp kibana-tmp:/usr/share/kibana/config $KIBANA_DIR/config

#sed -i 's@http://elasticsearch:9200@http://es:9200@' $KIBANA_DIR/config/kibana.yml
sed -i 's@xpack.monitoring.ui.container.elasticsearch.enabled: true@xpack.monitoring.ui.container.elasticsearch.enabled: false@' $KIBANA_DIR/config/kibana.yml
sed -i 's@monitoring.ui.container.elasticsearch.enabled: true@monitoring.ui.container.elasticsearch.enabled: false@' $KIBANA_DIR/config/kibana.yml

grep "^i18n.locale:" < $KIBANA_DIR/config/kibana.yml                                || sed -i '$ai18n.locale: zh-CN' $KIBANA_DIR/config/kibana.yml
grep "^xpack.encryptedSavedObjects.encryptionKey:" < $KIBANA_DIR/config/kibana.yml  || sed -i '$axpack.encryptedSavedObjects.encryptionKey: MyencryptionKey12345678901234567' $KIBANA_DIR/config/kibana.yml
grep "^xpack.security.encryptionKey:" < $KIBANA_DIR/config/kibana.yml               || sed -i '$axpack.security.encryptionKey: MyencryptionKey12345678901234567' $KIBANA_DIR/config/kibana.yml
grep "^xpack.reporting.encryptionKey:" < $KIBANA_DIR/config/kibana.yml              || sed -i '$axpack.reporting.encryptionKey: MyencryptionKey12345678901234567' $KIBANA_DIR/config/kibana.yml

cat $KIBANA_DIR/config/kibana.yml

chown -R 1000:1000 $KIBANA_DIR/
docker rm -f $name 2>/dev/null || true;
docker run -d --network mynet \
--name $name \
--restart always \
--privileged \
-e "TZ=Asia/shanghai" \
-e "ELASTICSEARCH_HOSTS=$es_host" \
-p $port_http:5601 \
-v $KIBANA_DIR/config:/usr/share/kibana/config ${kibana_image}

}



fun_install_nacos(){
docker run --net host --rm --name='wait4x' ${wait4x_image} mysql root:666666@tcp\(127.0.0.1:3306\)/mysql --interval 1s --timeout 360s && \
docker run -it --rm --network mynet  ${mysql5_image} mysql --host mysql57 --user root --password=666666 --loose-default-character-set=utf8 -e "CREATE DATABASE if not exists nacos DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;show databases;"



curl -fsSL --retry 10 https://mirror.ghproxy.com/https://github.com/alibaba/nacos/blob/develop/distribution/conf/mysql-schema.sql -o /tmp/nacos-mysql-schema.sql



docker run -i --rm --network mynet \
-v /tmp/nacos-mysql-schema.sql:/tmp/nacos-mysql-schema.sql \
${mysql5_image} mysql --host mysql57 --user root --password=666666 --loose-default-character-set=utf8 <<EOF
show variables like 'character%';
use nacos;
source /tmp/nacos-mysql-schema.sql;
EOF

docker run -i --rm --network mynet \
${mysql5_image} mysql --host mysql57 --user root --password=666666 --loose-default-character-set=utf8 <<'EOF'
use nacos;
INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);
INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
EOF


# https://github.com/nacos-group/nacos-docker/blob/master/example/standalone-mysql-5.7.yaml
nacos_home=$HOME/nacos
mkdir -p "${nacos_home}/plugins"
cat > ${nacos_home}/application.properties<<EOF
nacos.inetutils.ip-address=$ip4
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?serverTimezone=UTC&characterEncoding=utf8&connectTimeout=10000&socketTimeout=30000&autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=false
db.user.0=root
db.password.0=666666
EOF
docker rm -f nacos 2>/dev/null || true;
docker run -d --name=nacos --restart always \
--net host \
--privileged \
--ulimit nofile=40000:40000 \
-e MODE="standalone" \
-v ${nacos_home}/application.properties:/home/nacos/conf/application.properties \
-v ${nacos_home}/plugins:/home/nacos/plugins \
${nacos_image}
}

function fun_install_rocketmq_dashboard() {



if [ ! -f $HOME/rocketmq-dashboard/rocketmq-dashboard-1.0.1-SNAPSHOT.jar ]; then


if [[ -z "$proxy" ]]; then
    echo "must pass --proxy host:port,no need http:// start!" && exit 1
fi

if ! docker info &>/dev/null; then
    echo "need docker installed , please install docker first!" && exit 1
fi


rm -rf /tmp/rocketmq-dashboard
while true; do
    gitrepo="https://github.com/apache/rocketmq-dashboard.git"
    echo "try clone $gitrepo"
    sleep 1s && git clone ${gitrepo} --config "http.proxy=${proxy}" /tmp/rocketmq-dashboard && break
done

proxy_host=$(echo "${proxy}" | cut -d: -f1)
proxy_port=$(echo "${proxy}" | cut -d: -f2)


cat << EOF > /tmp/rocketmq-dashboard/settings.xml
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <pluginGroups>
  </pluginGroups>

  <proxies>

    <proxy>
      <active>true</active>
      <protocol>https</protocol>
      <host>${proxy_host}</host>
      <port>${proxy_port}</port>
      <nonProxyHosts>*.aliyun.com|*.nodejs.org</nonProxyHosts>
    </proxy>

  </proxies>

  <servers>
  </servers>

  <mirrors>
    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
  <profiles>
  </profiles>
</settings>
EOF

docker run -it --rm \
-v /tmp/rocketmq-dashboard:/tmp/rocketmq-dashboard \
maven:3.8.6-openjdk-18 \
bash -c "cd /tmp/rocketmq-dashboard && mvn clean package -Dmaven.test.skip=true --settings /tmp/rocketmq-dashboard/settings.xml"

mkdir -p $HOME/rocketmq-dashboard/
ls -l /tmp/rocketmq-dashboard/target/
/bin/cp -f /tmp/rocketmq-dashboard/target/*.jar $HOME/rocketmq-dashboard/


fi

docker rm -f rd 2>/dev/null || true;
docker run -d --name=rd --restart always \
--net host \
--privileged \
--ulimit nofile=40000:40000 \
-v $HOME/rocketmq-dashboard:/opt/data \
--entrypoint="" \
maven:3.8.6-openjdk-18 \
java -jar \
/opt/data/rocketmq-dashboard-1.0.1-SNAPSHOT.jar \
--rocketmq.config.namesrvAddrs=${ip4}:9876 \
--rocketmq.config.namesrvAddr=${ip4}:9876 \
--server.port=8888

}

fun_install_nginx(){
systemctl is-active nginx >/dev/null 2>&1 || apt install nginx-full -y;

cat >/etc/nginx/conf.d/seckill.conf<<-EOF
upstream seckill{
  server 192.168.6.35:8080 weight=10;
  server 192.168.6.35:8081 weight=10;
  keepalive 1000;
}

map \$http_upgrade \$connection_upgrade {
  default upgrade;
  '' close;
}

upstream websocket {
  ip_hash;
  server 192.168.6.35:8080 weight=10;
  server 192.168.6.35:8081 weight=10;
  keepalive 1000;
}

server {
  listen 8080;
  location / {
    root html;
    index index.html index.htm;
    proxy_pass http://seckill;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Accept-Encoding "";
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$remote_addr;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Forwarded-Port \$server_port;
    proxy_set_header X-Forwarded-Host \$host;
    proxy_set_header X-Forwarded-For \$remote_addr;
  }

  location /ws {
    proxy_pass http://websocket;
    proxy_http_version 1.1;
    proxy_set_header Host \$host;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \$connection_upgrade;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Forwarded-Port \$server_port;
    proxy_set_header X-Forwarded-Host \$host;
    proxy_set_header X-Forwarded-For \$remote_addr;
  }

}
EOF
cat </etc/nginx/conf.d/seckill.conf
nginx -t && systemctl reload nginx
}

fun_install_minio(){
docker rm -f minio 2>/dev/null || true
mkdir -p $HOME/minio/data
docker run -d --name=minio --restart always --network host \
-e "MINIO_ROOT_USER=minioadmin" \
-e "MINIO_ROOT_PASSWORD=minioadmin" \
-v $HOME/minio/data:/data \
${minio_image} server /data --address ":19000" --console-address ":19001"



sleep 5s;

docker run -i --rm --network host --entrypoint '' quay.io/minio/mc bash<<EOF
mc alias set myminio http://localhost:19000 minioadmin minioadmin;
mc admin user svcacct add --access-key "vUR3oLMF5ds8gWCP" --secret-key "odWFIZukYrw9dY0G5ezDKMZWbhU0S4oD" myminio minioadmin 2>/dev/null || true;
EOF
}

fun_install_nats(){
  docker rm -f nats 2>/dev/null || true;
  docker run \
    -d \
    --restart always \
    --network mynet \
    --name nats \
    -p 4222:4222 \
    -p 6222:6222  \
    -p 8222:8222 \
    nats:2.10.11
}


fun_rabbitmq_cluster(){
mkdir -p /opt/rabbitmq
cookie=/opt/rabbitmq/erlang.cookie
if [ ! -f $cookie ]; then
  cat < /dev/urandom | head -n 20 | md5sum | head -c 20 | tr '[:lower:]' '[:upper:]' > $cookie
  chown 999:999 $cookie
  chmod 600 $cookie
fi

local instance=2;
local port_tcp=5672;
local port_http=15672;
local port_hop=100;
for i in $(seq 1 "${instance}"); do
 ((port_tcp_next=port_tcp+(i-1)*port_hop))
 ((port_http_next=port_http+(i-1)*port_hop))
# echo $port_tcp_next
# echo $port_http_next
  local name="rr${i}"
  local hostname="rabbit${i}"
  local data="/opt/rabbitmq/${hostname}"
  mkdir -p "${data}"
  chown 999:999 "${data}"
  docker rm -f "$name" 2>/dev/null || true
  docker run \
  -d \
  -p "${port_http_next}":15672 \
  -p "${port_tcp_next}":5672 \
  --restart always \
  --name "${name}" \
  --network mynet \
  --hostname "${hostname}" \
  -v "${data}":/var/lib/rabbitmq \
  -v "${cookie}":/var/lib/rabbitmq/.erlang.cookie \
  -e RABBITMQ_DEFAULT_USER=admin \
  -e RABBITMQ_DEFAULT_PASS=admin \
  -e RABBITMQ_NODENAME=rabbit@"${hostname}" \
  rabbitmq:3.12.13-management
done

sleep 4s;

if [[ "${instance}" -ge 2 ]]; then
for i in $(seq 2 "${instance}"); do
  local name="rr${i}"
  docker exec -i "${name}" bash -c "rabbitmqctl stop_app && rabbitmqctl reset && rabbitmqctl join_cluster rabbit@rabbit1 && rabbitmqctl start_app"
done
fi


}




if [ ! -f /INIT_OK ]; then
  fun_system && fun_pkg && touch /INIT_OK
fi
fun_add_mynet

fun_install_redis
fun_install_mysql
fun_initdb




docker rm -f es 2>/dev/null || true;
docker rm -f kibana 2>/dev/null || true;
fun_install_es "7"
fun_install_kibana "7"
fun_install_nacos
fun_install_rocketmq
# fun_install_rocketmq_dashboard
fun_install_nginx
fun_install_minio
fun_install_mongo
fun_install_nats

fun_rabbitmq_cluster